import React, { Component } from 'react';
const queryString = require('query-string');
import RequestNoteForm from './components/RequestNoteForm';
import { withRouter } from 'react-router-dom';
import { Loading, Button } from '@alifd/next';
import request from '../../instances/request';
import { noteTypes } from '../../conf/noteTypeConfig';
import { formConfigs } from './../../conf/noteFormConfig';
import ConstructionExportTable from './templates/ConstructionExportConfig.js';
import RequestChangeExportTable from './templates/RequestChangeExportConfig.js';
import ProjectTestExportTable from './templates/ProjectTestExportConfig.js';
import ExternalTestExportConfig from './templates/ExternalTestExportConfig.js';
import MaintainExportConfig from './templates/MaintainExportConfig.js';
import './index.scss';
import { minHeight } from "../../conf/config";
const moment = require('moment');

@withRouter
export default class RequestNote extends Component {
  static displayName = 'RequestNote';

  constructor(props) {
    super(props);
    this.state = {
      __loading: true,
      formConfig: [],
      actions: {
        enableChange: false,  // 是否允许修改
        showStatus: false,  // 是否显示进度条
        showExport: false,  // 是否显示导出
        showApprovalButton: false,  // 是否显示审批按钮
        showCommitButton: false,  // 是否显示提交按钮
        showReason: false,  // 是否显示被拒理由
        showCloseButton: false,  // 是否显示请求关闭按钮
        showHint: false, // 是否显示提示文本
        showStep1001Button: false,  // 填写变更实施现场描述
        showStep1002Button: false, // 第三方联系人不能拒绝
        showStep1005Button: false,  // 变更核实者签名且不能拒绝
        showComStep1006Button: false, // 普通用户填写变更回顾代码、变更说明代码、变更关闭代码
        showStep1007And1008And1009Button: false,  // 特殊审批员审批
        showWellFormedTable: true,  // 是否展示格式更好的表格
        showResetButton: false, // 是否展示重置按钮
      },
      formData: {},
      title: '',
      approvers: [],
      moreSteps: [],
      step: 0,
      reason: '',
      isRejected: false,
      oid: '',
      type: '',
      hint: '',
      exportTableConfig: [],
    };
  }

  async getNoteContent(oid) {
    const res = await request
      .post('/staff/requestNote/content',{
        oid,
      });
    let { code, msg } = res.data;
    if( code !== 0 ) {
      throw new Error(`得到申请单内容接口code为${code}`);
    }
    let { requestNote, isApprover, type, step, reason, isRejected } = msg;
    // 特殊处理
    requestNote.beginTime = requestNote.beginTime && moment(requestNote.beginTime);  // todo: 如果直接传回字符串的话，前端根据字符串显示会有UTC时差，因此要返回moment对象，这是飞冰内部没有处理好
    requestNote.endTime = requestNote.endTime && moment(requestNote.endTime);
    requestNote.requestChangeDate = requestNote.requestChangeDate && moment(requestNote.requestChangeDate);
    requestNote.requestChangeTime = requestNote.requestChangeTime && moment(requestNote.requestChangeTime);
    requestNote.beginTimeConfirm = requestNote.beginTimeConfirm && moment(requestNote.beginTimeConfirm);
    requestNote.endTimeConfirm = requestNote.endTimeConfirm && moment(requestNote.endTimeConfirm);
    requestNote.planTime = requestNote.planTime && moment(requestNote.planTime);

    return {
      requestNote,
      isApprover,
      isRejected: !!isRejected,
      type,
      step,
      reason,
    }
  }

  async setRequestNoteContent() {
    const { location } = this.props;
    let { oid, type, ut } = queryString.parse(location.search);  // ut即userType
    let actions = this.state.actions;  // 默认权限最小
    let formConfig = [];
    let title = '';
    let hint = '';
    let approvers = [];
    let moreSteps = [];

    if( oid == null || oid === undefined ) {  // 新增申请单
      actions.showCommitButton = true;
      actions.enableChange = true;
      actions.showWellFormedTable = false;
      // actions.showHint = true;
      noteTypes.forEach((ele, idx) => {
        if( ele.enName === type ) {
          title = ele.name;
          hint = ele.hint;
          formConfig = formConfigs[idx];
          approvers = ele.approvers;
          if(ele.moreSteps) {
            moreSteps = ele.moreSteps;
          }
        }
      });
      this.setState({
        formConfig,
        actions,
        title,
        type,
        hint,
        __loading: false,
        approvers,
        moreSteps,
      })
    } else {  // 需要获取申请单详细内容和用户的操作类型['user', 'approver']
      let { requestNote, isApprover, type, step, reason, isRejected } = await this.getNoteContent(oid);
      let { title } = requestNote || requestNote.title;
      let exportTableConfig = [];
      switch (type) {
        case 'Construction':
          exportTableConfig = ConstructionExportTable;
          break;
        case 'RequestChange':
          exportTableConfig = RequestChangeExportTable;
          break;
        case 'ProjectTest':
          exportTableConfig = ProjectTestExportTable;
          break;
        case 'ExternalTest':
          exportTableConfig = ExternalTestExportConfig;
          break;
        case 'Maintain':
          exportTableConfig = MaintainExportConfig;
          break;
      }
      actions.showWellFormedTable = true;

      if( step === 1001 ) {  // 变更申请单特殊情况——填写变更实施现场情况描述
        if(isRejected) {
          actions.showReason = true;
        }
        if ( ut === 'com' ) {
          actions.showStep1001Button = true;
        }
        if(!! isRejected) {
          actions.showReason = true;
        }
        actions.showStatus = true;
      } else if( step === 1002) {  // 特殊情况——第三方联系人签名
        if (ut === 'app' ) {
          actions.showStep1002Button = true;
        }
        actions.showStatus = true;
      } else if( step === 1003 || step === 1004) { // 如果是审批
        if( ut === 'app') {
          actions.showApprovalButton = true;
        }
        actions.showStatus = true;
      } else if( step === 1005 ) {  // 变更申请单特殊情况——变更核实者审批核实且不能拒绝
        if( ut === 'app' ) {
          actions.showStep1005Button = true;
        }
        actions.showStatus = true;
      } else if( step === 1006 && ut === 'com' ) {  // 普通用户填写/重新填写
        if( !!isRejected ) {  // 展示信息并且可以重新填写提交
          actions.showStatus = true;
          actions.showReason = true;
          actions.showComStep1006Button = true;
        } else {  // 展示信息并且可以提交审批
          actions.showStatus = true;
          actions.showComStep1006Button = true;
        }
      } else if( step === 1003 && ut === 'app' ) { // 审批员审批
        if( !!isRejected ) {  // 只展示信息，什么也不做
          actions.showStatus = true;
          actions.showReason = true;
        }
      } else if( step === 1007 || step === 1008 || step === 1009) {
        actions.showStatus = true;
        actions.showApprovalButton = true;
      } else if( step === 1010 ) {  // 如果变更申请走到了最后一步
        actions.showStatus = true;
        actions.showCloseButton = true;
      } else if( !!isRejected ) {  // 被拒绝的申请单
        actions.showReason = true;
        actions.showStatus = true;
        actions.showResetButton = true;  // 展示重置按钮
      } else if( step === 0 ) {  // 未提交的申请单
        actions.showCommitButton = true;
        actions.enableChange = true;
        actions.showWellFormedTable = false;
        // actions.showHint = true;
      } else if( step > 0 && step < 1000 && !isApprover ) {  // 查看审批中的申请单
        actions.showStatus = true;
      } else if( step > 0 && step < 1000 && isApprover ) {  // 当前审批人员审批申请单
        actions.showApprovalButton = true;
        actions.showStatus = true;
      } else if( step === 1000 && ut === 'com') {  // 用户查看进行中的申请单, com即common
        actions.showStatus = true;
        actions.showCloseButton = true;
      } else if(step === 1000 && ut === 'app') {  // 审批人员查看进行中的申请单，不能关闭, ap即approver
        actions.showStatus = true;
      } else if( step === 2000 ) { // 查看已关闭的申请单
        actions.showStatus = true;
        actions.showExport = true;
      }

      if(ut === 'com') {   // 如果是从申请区域点进去的，则统一不给审批按钮，这样防止用户产生困惑
        actions.showApprovalButton = false;
      }

      noteTypes.forEach((ele, idx) => {
        if( ele.enName === type ) {
          formConfig = formConfigs[idx];
          approvers = ele.approvers;
          hint = ele.hint;
          if (ele.moreSteps) {
            moreSteps = ele.moreSteps;
          }
        }
      });


      this.setState({
        formData: requestNote,
        actions,
        formConfig,
        title,
        __loading: false,
        approvers,
        step,
        reason,
        type,
        isRejected: !!isRejected,
        oid,
        hint,
        moreSteps,
        exportTableConfig,
      })
    }
  }

  async componentDidMount() {
    await this.setRequestNoteContent();
  }

  render() {
    return(
      this.state.__loading ? <Loading tip='加载中' size="large" fullScreen/> :
        <div style={{ minHeight }}>
          <div style={{ textAlign: 'center', height: '20px', backgroundColor: '#50AFCA', color: 'white' }}>
            {/*<Button type='primary' onClick={(e) => {*/}
              {/*e.preventDefault();*/}
              {/*this.setState({*/}
                {/*__loading: true,*/}
                {/*formConfig: [],*/}
                {/*actions: {*/}
                  {/*enableChange: false,  // 是否允许修改*/}
                  {/*showStatus: false,  // 是否显示进度条*/}
                  {/*showExport: false,  // 是否显示导出*/}
                  {/*showApprovalButton: false,  // 是否显示审批按钮*/}
                  {/*showCommitButton: false,  // 是否显示提交按钮*/}
                  {/*showReason: false,  // 是否显示被拒理由*/}
                  {/*showCloseButton: false,  // 是否显示请求关闭按钮*/}
                  {/*showHint: false, // 是否显示提示文本*/}
                  {/*showStep1001Button: false,  // 填写变更实施现场描述*/}
                  {/*showStep1002Button: false,  // 变更核实者同意（填写文字）且不能拒绝*/}
                  {/*showComStep1003Button: false, // 普通用户填写变更回顾代码、变更说明代码、变更关闭代码*/}
                  {/*showStep1004And1005And1006Button: false,  // 特殊审批员审批*/}
                {/*},*/}
                {/*formData: {},*/}
                {/*title: '',*/}
                {/*approvers: [],*/}
                {/*moreSteps: [],*/}
                {/*step: 0,*/}
                {/*reason: '',*/}
                {/*isRejected: 0,*/}
                {/*oid: '',*/}
              {/*}, () => {*/}
                {/*this.setRequestNoteContent();*/}
              {/*})*/}
            {/*}}>下一页</Button>*/}
          </div>
          <RequestNoteForm
            type={this.state.type}
            formConfig={this.state.formConfig}
            formData={this.state.formData}
            actions={this.state.actions}
            title={this.state.title}
            approvers={this.state.approvers}
            step={this.state.step}
            reason={this.state.reason}
            isRejected={this.state.isRejected}
            oid={this.state.oid}
            moreSteps={this.state.moreSteps}
            hint={this.state.hint}
            exportTableConfig={this.state.exportTableConfig}
          />
        </div>
    );
  }
}
